import { ref } from 'vue'

export interface Tab {
  webContentsId: number
  loading: boolean
  favicon: string
  title: string
  url: string
  canGoBack: boolean
  canGoForward: boolean
}

const tabs = ref<Tab[]>([])
const activeTabIndex = ref(-1)

// Create
function startCreateTab(val: string) {
  window.ipc.sendViewStartCreate(val)
}
function createTab(val: Tab) {
  tabs.value.push(val)
}
window.ipc.onViewMainFrameCreated(id => {
  createTab({
    webContentsId: id,
    loading: false,
    favicon: '',
    title: '正在加载',
    url: '',
    canGoBack: false,
    canGoForward: false
  })
  activeTab(tabs.value.length - 1)
})

// Update
function startChangeTabHistory(id: number, opt: 'back' | 'forward' | 'refresh') {
  window.ipc.sendViewStartHistoryChange(id, opt)
}
function updateTab(id: number, tab: Partial<Tab>) {
  const tIdx = tabs.value.findIndex(i => i.webContentsId === id)
  if (tIdx >= 0) {
    tabs.value[tIdx] = { ...tabs.value[tIdx], ...tab }
  }
}
window.ipc.onViewDidStartLoading(id => {
  updateTab(id, { loading: true })
})
window.ipc.onViewDidStartNavigation((id, url) => {
  updateTab(id, { url })
})
window.ipc.onViewDidStopLoading((id, canGoBack, canGoForward) => {
  updateTab(id, {
    loading: false,
    canGoBack,
    canGoForward
  })
})
window.ipc.onViewPageFaviconUpdated((id, favicons) => {
  if (favicons.length > 0) {
    updateTab(id, { favicon: favicons[0] })
  }
})
window.ipc.onViewPageTitleUpdated((id, title) => {
  if (title) {
    updateTab(id, { title })
  }
})

// Active & Remove
function activeTab(val: number) {
  window.ipc.sendViewActive(tabs.value[val].webContentsId)
  activeTabIndex.value = val
}
function removeTab(val: number) {
  const len = tabs.value.length

  // 通知主线程删除相应的 BrowserView，并激活下一个 BrowserView（仅仅当删除的激活的tab时）
  const id = tabs.value[val].webContentsId
  let nextId: number | null = null
  let nextIndex = activeTabIndex.value
  if (val === activeTabIndex.value) {
    if (val === 0) {
      nextIndex = -1
    } else if (activeTabIndex.value === len - 1) {
      nextIndex = len - 2
      nextId = tabs.value[nextIndex].webContentsId
    } else {
      nextId = tabs.value[val + 1].webContentsId
    }
  } else if (val < activeTabIndex.value) {
    nextIndex = activeTabIndex.value - 1
  }
  window.ipc.sendViewRemove(id, nextId)
  // 删除 tab, 并更新 activeTbaIndex
  tabs.value.splice(val, 1)
  activeTabIndex.value = nextIndex
}

export default function useTabs() {
  return {
    tabs,
    activeTabIndex,
    startCreateTab,
    startChangeTabHistory,
    activeTab,
    removeTab
  }
}
